package com.oe.market.modules.ele.service;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.google.gson.Gson;
import com.oe.market.modules.base.ex.BusinessException;
import com.oe.market.modules.ele.model.bean.Cookie;
import com.oe.market.modules.ele.model.bean.CookieUseCount;
import com.oe.market.modules.ele.model.bean.RedPackage;
import com.oe.market.modules.ele.model.dao.AccountDao;
import com.oe.market.modules.ele.model.dao.CookieDao;
import com.oe.market.modules.ele.model.dao.CookieUseCountDao;
import com.oe.market.modules.ele.model.dao.RedPackageDao;
import com.oe.market.modules.ele.model.dto.EleRedPackageDto;
import com.oe.market.modules.ele.model.dto.EleRequestDto;
import com.oe.market.modules.ele.model.dto.RedPackageResponseDto;
import com.oe.market.modules.ele.model.mapper.EleRequestMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.List;


public class EleRequestService {
    private static final Logger log = LoggerFactory.getLogger(EleRequestService.class);

    public String add(EleRequestDto eleRequestDto, Integer accountId) {
        try {
            // 添加消息结构
            Gson gson = new Gson();
            EleRedPackageDto eleRedPackageDto = gson.fromJson(eleRequestDto.body,EleRedPackageDto.class);

            if (null == eleRedPackageDto.phone
                || eleRedPackageDto.phone.isEmpty()) {
                return "手机号非法";
            }
            CookieUseCount cookieUseCount = new CookieUseCount();
            cookieUseCount.setAvatar(eleRedPackageDto.weixinAvatar);
            cookieUseCount.setFromAccountId(accountId);
            cookieUseCount.setNickname(eleRedPackageDto.weixinUsername);
            cookieUseCount.setPhone(eleRedPackageDto.phone);

            {
                String snsHash = calcMD2(eleRequestDto.cookie);
                if (null == snsHash) {
                    return "小号非法";
                }
                if (0 == CookieUseCountDao.me.findBySnsHash(snsHash).size()
                        && 0 == CookieUseCountDao.me.findByPhone(cookieUseCount.getPhone()).size()) {
                    cookieUseCount.setSnsHash(snsHash);
                }
                else {
                    return "该小号已经存在";
                }
            }

            EleRequestMapper eleRequestMapper = new EleRequestMapper(eleRequestDto);
            Cookie cookie = eleRequestMapper.getCookie();
            cookie.setSnsHash(cookieUseCount.getSnsHash());
            if (null != CookieDao.me.append(cookie)) {
                return  "未知错误";
            }
            if (!isValidRobot(cookie)) {
                return "不是有效的小号";
            }
            List<Cookie> cookies = CookieDao.me.findLastBySnsHash(cookie.getSnsHash());
            cookieUseCount.setInfoId(cookies.get(0).getCookieId());

            String result = CookieUseCountDao.me.append(cookieUseCount);
            if (null != result) {
                return  result;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("request: " + new Gson().toJson(eleRequestDto));
            return "非法请求";
        }
        return null;
    }


    public static String calcMD2(String cookie) {
        String [] strings = cookie.split(";");
        for (String str : strings) {
            if (0 == str.indexOf("snsInfo[")) {
                // 计算sign
                Digester md2 = new Digester(DigestAlgorithm.MD2);
                try {
                    return md2.digestHex(str.getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    return null;
                }
            }
        }
        return null;
    }

    public static boolean isValidRobot(Cookie checkCookie) {
        EleRedPackageService eleRedPackageService = new EleRedPackageService();
        RedPackage redPackage = eleRedPackageService.getUselessRedPackage();
        if (null == redPackage) {
            // @bug
            log.error("废弃红包不充足，这个小号需要人工检验: " + checkCookie.snsHash);
            return true;
        }
        RedPackageResponseDto redPackageResponseDto = null;
        try {
            redPackageResponseDto = eleRedPackageService.takeRedPackage(redPackage.groupSn, checkCookie);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        if (null == redPackageResponseDto) {
            return false;
        }
        Integer checkPos = redPackageResponseDto.getPromotionRecords().size();
        if (checkPos > redPackage.currentPos) {
            RedPackageDao.me.updateCurrent(redPackage.groupSn, checkPos);
            return true;
        }

        // 最后一波验证
        List<RedPackageResponseDto.PromotionRecord> promotionRecords = redPackageResponseDto.getPromotionRecords();
        Gson gson = new Gson();
        EleRedPackageDto eleRedPackageDto = gson.fromJson(checkCookie.body,EleRedPackageDto.class);
        for (RedPackageResponseDto.PromotionRecord promotionRecord : promotionRecords) {

            if (promotionRecord.getSnsUsername().equals(eleRedPackageDto.weixinUsername)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
    }
}
